package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.TaiKhoanM;
import net.sf.json.JSONObject;
import dao.TaiKhoanD;

@WebServlet("/TaiKhoanServlet")
public class TaiKhoanServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private TaiKhoanD dao;
	//private CryptoLibrary code;
       
    /**
     * @throws Exception 
     * @see HttpServlet#HttpServlet()
     */
    public TaiKhoanServlet() throws Exception {
        super();
        this.dao = new TaiKhoanD();
        //this.code = new CryptoLibrary();
    }

    /**
	 * Destruction of the servlet.
	 */
	public void destroy() {
		super.destroy();
	}
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		
		String flag = request.getParameter("flag");
		try {
			if (flag == null || "".equals(flag.trim())) {
				showTK(request, response);
			}else if ("add".equals(flag.trim())) {
				String ma = request.getParameter("ma_nguoi_dung");
				String ten = request.getParameter("ten_nguoi_dung");
				String user = request.getParameter("ten_dang_nhap");
				String pass = request.getParameter("mat_khau");
				String nhom = request.getParameter("nhom_nguoi_dung");
				addTK(ma,ten,user,pass,nhom,request,response);
			}else if ("edit".equals(flag.trim())) {
				String id = request.getParameter("id_nguoi_dung");
				String ma = request.getParameter("ma_nguoi_dung");
				String ten = request.getParameter("ten_nguoi_dung");
				String nhom = request.getParameter("nhom_nguoi_dung");
				editTK(Integer.parseInt(id), ma, ten, nhom, request, response);
			}else if ("changepass".equals(flag.trim())) {
				String id = request.getParameter("id_nguoi_dung");
				String mat_khau = request.getParameter("mat_khau_moi");
				editMatKhau(Integer.parseInt(id), mat_khau,request, response);
			}else if ("remove".equals(flag.trim())) {
				String id = request.getParameter("id");
				deleteTK(Integer.parseInt(id), request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @function show TaiKhoan
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void showTK(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String pageCount = request.getParameter("page");
		String rowsCount = request.getParameter("rows");
		String search=request.getParameter("searchTen")==null?"":request.getParameter("searchTen");
		
		int page = (pageCount == null || "".equals(pageCount)) ? 1 : Integer.valueOf(pageCount);
		int rows = (rowsCount == null || "".equals(rowsCount)) ? 10 : Integer.valueOf(rowsCount);
		
		int offSet = (page - 1) * rows;
		int allCount = dao.searchTK(search).size();
		
		returnMap.put("total", allCount);
		returnMap.put("rows", dao.getLimit(search, offSet, rows));
		
		String returnString = JSONObject.fromObject(returnMap).toString();
		PrintWriter out = response.getWriter();
		out.println(returnString);
		out.flush();
		out.close();
	}
	
	/**
	 * @function add TaiKhoan
	 * @param ma_nguoi_dung
	 * @param ten_nguoi_dung
	 * @param ten_dang_nhap
	 * @param mat_khau
	 * @param nhom_nguoi_dung
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void addTK(String ma_nguoi_dung, String ten_nguoi_dung, String ten_dang_nhap, String mat_khau, String nhom_nguoi_dung, HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		TaiKhoanM tk = new TaiKhoanM();
		tk.setMa_nguoi_dung(ma_nguoi_dung);
		tk.setTen_nguoi_dung(ten_nguoi_dung);
		tk.setTen_dang_nhap(ten_dang_nhap);
		tk.setMat_khau(mat_khau);
		tk.setNhom_nguoi_dung(nhom_nguoi_dung);
		if(dao.Insert(tk)==true){
			map.put("success", "true");
			map.put("msg", "Thêm thành công");
		} else {
			map.put("success", "false");
			map.put("msg", "Lỗi thêm dữ liệu");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
	
	/**
	 * @function edit TaiKhoan
	 * @param id_nguoi_dung
	 * @param ma_nguoi_dung
	 * @param ten_nguoi_dung
	 * @param nhom_nguoi_dung
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void editTK(int id_nguoi_dung, String ma_nguoi_dung, String ten_nguoi_dung, String nhom_nguoi_dung , HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		TaiKhoanM tk = new TaiKhoanM();
		tk.setId_nguoi_dung(id_nguoi_dung);
		tk.setMa_nguoi_dung(ma_nguoi_dung);
		tk.setTen_nguoi_dung(ten_nguoi_dung);
		tk.setNhom_nguoi_dung(nhom_nguoi_dung);
		if(dao.Update(tk)==true){
			map.put("success", "true");
			map.put("msg", "Sửa thành công");
		} else {
			map.put("success", "false");
			map.put("msg", "Lỗi sửa dữ liệu");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
	
	/**
	 * @function edit MatKhau
	 * @param id_nguoi_dung
	 * @param mat_khau
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void editMatKhau(int id_nguoi_dung, String mat_khau, HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
			TaiKhoanM tk = new TaiKhoanM();
			tk.setId_nguoi_dung(id_nguoi_dung);
			tk.setMat_khau(mat_khau);
			if(dao.UpdatePass(tk)){
				map.put("success", "true");
				map.put("msg", "Sửa thành công");
			} else {
				map.put("success", "false");
				map.put("msg", "Lỗi sửa dữ liệu");
			}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
	
	/**
	 * @function delete TaiKhoan
	 * @param id
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void deleteTK(int id, HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if(dao.Delete(id)==true){
			map.put("success", "true");
			map.put("msg", "Xóa thành công");
		} else {
			map.put("success", "false");
			map.put("msg", "Lỗi xóa dữ liệu");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
}
